package com.dy.yunying.biz.service.manage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.TtExtendPackageDO;
import com.dy.yunying.biz.dao.manage.ext.TtExtendPackageMapperExt;
import com.dy.yunying.biz.service.manage.TtExtendPackageService;
import com.dy.yunying.biz.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.feign.RemoteTtAccesstokenService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：lile
 * @date ：2021/8/5 13:37
 * @description：
 * @modified By：
 */
@Transactional(transactionManager = "main3399TransactionManager", rollbackFor = Exception.class)
@Service
@Slf4j
public class TtExtendPackageServiceImpl extends ServiceImpl<TtExtendPackageMapperExt, TtExtendPackageDO> implements TtExtendPackageService {

	@Autowired
	private RemoteTtAccesstokenService remoteTtAccesstokenService;

	@Autowired
	private TtExtendPackageMapperExt ttExtendPackageMapperExt;

	@Autowired
	private TtExtendPackageService ttExtendPackageService;


	@Override
	public void queryExtendPackage(String param) {

		XxlJobLogger.log("-----------------查询头条分包明细开始---------------------");
		long start = System.currentTimeMillis();

		String urlDetail = "https://ad.oceanengine.com/open_api/2/tools/app_management/extend_package/list/";

		// 查询明细中 不是已发版完成的  广告账户和应用包Id
		List<TtExtendPackageDO> extendPackageDOList = ttExtendPackageMapperExt.queryAdvertiserIdByStatus();
		if (ObjectUtils.isNotEmpty(extendPackageDOList)) {
			//按广告账户和包ID去重
			List<TtExtendPackageDO> distinctList = extendPackageDOList.stream()
					.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
							Comparator.comparing(v -> v.getAdvertiserId()+v.getPackageId()))), ArrayList::new));

			distinctList.forEach(data -> {
				String advertiserId = data.getAdvertiserId();
				String packageId = data.getPackageId();
				// 调用头条API《创建应用分包》
				R dataResult = remoteTtAccesstokenService.fetchAccesstoken(SecurityConstants.FROM_IN, advertiserId);
				String accessToken = (String) dataResult.getData();
				int page = 1;
				while (true) {
					// 创建成功后调用头条
					Map<String, Object> datalist = new HashMap<String, Object>();
					datalist.put("advertiser_id", advertiserId);
					datalist.put("package_id", packageId);
					datalist.put("page",page);
					datalist.put("page_size",10);
					// 调用头条分包明细接口
					String result = OEHttpUtils.doGet(urlDetail, datalist, accessToken);
					ResponseBean resBeanDetail = JSON.parseObject(result, ResponseBean.class);
					if (resBeanDetail != null && "0".equals(resBeanDetail.getCode())) {
						JSONObject jsonObj = resBeanDetail.getData();
						JSONArray arr = JSON.parseArray(String.valueOf(jsonObj.get("list")));
						String page_info = jsonObj.getString("page_info");
						if (arr.size() > 0) {
							for (Object obj : arr) {
								JSONObject jsonObject = (JSONObject) obj;

								TtExtendPackageDO ttExtendPackageDO = new TtExtendPackageDO();
								ttExtendPackageDO.setReason(jsonObject.getString("reason"));
								ttExtendPackageDO.setStatus(jsonObject.getString("status"));
								ttExtendPackageDO.setTtUpdateTime(jsonObject.getString("update_time"));
								ttExtendPackageDO.setVersionName(jsonObject.getString("version_name"));

								ttExtendPackageDO.setChannelId(jsonObject.getString("channel_id"));
								ttExtendPackageDO.setDownloadUrl(jsonObject.getString("download_url"));
								String channel_id = jsonObject.getString("channel_id");

								TtExtendPackageDO extendPackageDO = ttExtendPackageService.getOne(Wrappers.<TtExtendPackageDO>query()
										.lambda().in(TtExtendPackageDO::getChannelId, channel_id).eq(TtExtendPackageDO::getIsDeleted, 0).last("LIMIT 1"));
								if (extendPackageDO != null) {
									if (!extendPackageDO.getChannelId().equals("PUBLISHED")) {
										ttExtendPackageMapperExt.updateByChannelId(ttExtendPackageDO);
									}
								}
							}
						}
						JSONObject jsonObject = JSONObject.parseObject(page_info);
						Long total_page = jsonObject.getLong("total_page");
						if (page >= total_page) {
							break;
						}
						page++;
					} else {
						log.info("获取头条分包明细异常：{},广告账户:{},token:{}",JSON.toJSONString(resBeanDetail),advertiserId,accessToken);
						break;
					}
				}
			});

		}

		long end = System.currentTimeMillis();
		XxlJobLogger.log("-----------------查询头条分包明细结束，耗时：" + (end - start) / 1000 + "秒---------------------");
	}
}
